{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "automatic_differentiation.ipynb",
      "version": "0.3.2",
      "provenance": [],
      "private_outputs": true,
      "collapsed_sections": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "t09eeeR5prIJ"
      },
      "source": [
        "##### Copyright 2018 The TensorFlow Authors."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "form",
        "colab_type": "code",
        "id": "GCCk8_dHpuNf",
        "colab": {}
      },
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "xh8WkEwWpnm7"
      },
      "source": [
        "# Otomatik degisim ve egim banti"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "idv0bPeCp325"
      },
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/tr/r1/tutorials/eager/automatic_differentiation.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/tr/r1/tutorials/eager/automatic_differentiation.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "vDJ4XzMqodTy"
      },
      "source": [
        "Bir onceki egitim kitapciginda 'Tensor'lari ve onlar ustunde kullanabileceginiz operasyonlari tanittik. Bu kitapcikta ise makine ogrenmesi modellerinin eniyilenmesinde onemli bir teknik olan [otomatik degisimi](https://en.wikipedia.org/wiki/Automatic_differentiation) ogrenecegiz."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "GQJysDM__Qb0"
      },
      "source": [
        "## Kurulum\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "OiMPZStlibBv",
        "colab": {}
      },
      "source": [
        "from __future__ import absolute_import, division, print_function, unicode_literals\n",
        "\n",
        "import tensorflow as tf\n",
        "\n",
        "tf.enable_eager_execution()"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "1CLWJl0QliB0"
      },
      "source": [
        "## Egim bantlari\n",
        "\n",
        "TensorFlow'un [tf.GradientTape](https://www.tensorflow.org/api_docs/python/tf/GradientTape) API'si otomatik degisim yani girdi degiskenlerine bagli olarak hesaplanan egimin hesaplanisini hali hazirda bize saglar. Tensorflow `tf.GradientTape` kapsaminda yapilan butun operasyonlari bir \"tape(bant)\"e \"kaydeder\". Tensorflow daha sonra \"kaydedilmis\" egimleri, bu bant ve her bir kayitla iliskili egim verilerini [ters mod degisimi](https://en.wikipedia.org/wiki/Automatic_differentiation) kullanarak hesaplar.\n",
        "\n",
        "Ornegin:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "bAFeIE8EuVIq",
        "colab": {}
      },
      "source": [
        "x = tf.ones((2, 2))\n",
        "\n",
        "with tf.GradientTape() as t:\n",
        "  t.watch(x)\n",
        "  y = tf.reduce_sum(x)\n",
        "  z = tf.multiply(y, y)\n",
        "\n",
        "# Orjinal girdi tensoru x'e gore z'nin turevi\n",
        "dz_dx = t.gradient(z, x)\n",
        "for i in [0, 1]:\n",
        "  for j in [0, 1]:\n",
        "    assert dz_dx[i][j].numpy() == 8.0"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "N4VlqKFzzGaC"
      },
      "source": [
        "Ayrica \"kaydedilmis\" 'tf.GradientTape' kapsaminda hesaplanan ara degerlere gore ciktilari egimini de isteyebilirsiniz."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "7XaPRAwUyYms",
        "colab": {}
      },
      "source": [
        "x = tf.ones((2, 2))\n",
        "\n",
        "with tf.GradientTape() as t:\n",
        "  t.watch(x)\n",
        "  y = tf.reduce_sum(x)\n",
        "  z = tf.multiply(y, y)\n",
        "\n",
        "# Banti kullanarak ara deger y'ye gore z'nin turevini hesaplayabiliriz.\n",
        "dz_dy = t.gradient(z, y)\n",
        "assert dz_dy.numpy() == 8.0"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "ISkXuY7YzIcS"
      },
      "source": [
        "GradientTape.gradient() yontemini cagirdimizda GradientTape tarafindan tutulan kaynaklar serbest birakilir. Ayni degerleri kullanarak birden fazla egim hesaplamak istiyorsaniz 'persistent(kalici)' egim banti olusturmalisiniz. Bu sayede bant nesnesi cop toplayicisi tarafindan toplanip kaynaklar serbest birakildikca 'gradient()' yontemini bircok kere cagirmamiza izin verir. Ornegin:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "zZaCm3-9zVCi",
        "colab": {}
      },
      "source": [
        "x = tf.constant(3.0)\n",
        "with tf.GradientTape(persistent=True) as t:\n",
        "  t.watch(x)\n",
        "  y = x * x\n",
        "  z = y * y\n",
        "dz_dx = t.gradient(z, x)  # 108.0 (4*x^3 at x = 3)\n",
        "dy_dx = t.gradient(y, x)  # 6.0\n",
        "del t  # Referansi banta indirgeyelim"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "6kADybtQzYj4"
      },
      "source": [
        "### Kontrol akimini kaydedelim\n",
        "\n",
        "Bantlar operasyonlar yurutuldukce kaydettigi icin, Python kontrol akimlari (`if`ler ve `while`lar gibi) dogal olarak islenir:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "9FViq92UX7P8",
        "colab": {}
      },
      "source": [
        "def f(x, y):\n",
        "  output = 1.0\n",
        "  for i in range(y):\n",
        "    if i > 1 and i < 5:\n",
        "      output = tf.multiply(output, x)\n",
        "  return output\n",
        "\n",
        "def grad(x, y):\n",
        "  with tf.GradientTape() as t:\n",
        "    t.watch(x)\n",
        "    out = f(x, y)\n",
        "  return t.gradient(out, x)\n",
        "\n",
        "x = tf.convert_to_tensor(2.0)\n",
        "\n",
        "assert grad(x, 6).numpy() == 12.0\n",
        "assert grad(x, 5).numpy() == 12.0\n",
        "assert grad(x, 4).numpy() == 4.0\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "DK05KXrAAld3"
      },
      "source": [
        "### Yuksek-sirali egimler\n",
        "\n",
        "`GradientTape` kapsam yoneticisindeki operasyonlar otomatik degisim icin kaydedilir. Eger egimler bu kapsamda hesaplandiysa onlar da ayni sekilde kaydedilir. Sonuc olarak, ayni API'yi kullanarak yuksek-sirali egimleri hesaplayabiliriz. Ornegin:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "cPQgthZ7ugRJ",
        "colab": {}
      },
      "source": [
        "x = tf.Variable(1.0)  # 1.0 degerine ilklenmis bir Tensorflow degiskeni olusturalim\n",
        "\n",
        "with tf.GradientTape() as t:\n",
        "  with tf.GradientTape() as t2:\n",
        "    y = x * x * x\n",
        "  # 't' kapsam yoneticisi icerisinde egimi hesaplayalim\n",
        "  # ki bu egim hesaplanmasinin turevlenebilir oldugu anlamina gelir.\n",
        "  dy_dx = t2.gradient(y, x)\n",
        "d2y_dx2 = t.gradient(dy_dx, x)\n",
        "\n",
        "assert dy_dx.numpy() == 3.0\n",
        "assert d2y_dx2.numpy() == 6.0"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "4U1KKzUpNl58"
      },
      "source": [
        "## Bir sonraki adimlar\n",
        "\n",
        "Bu kitapcikta egim hesaplanmasinin TensorFlow'da nasil yapildigini gorduk. Simdi sinir agimizi olusturmak ve egitmek icin gerekli ilkellerin hepsine sahibiz."
      ]
    }
  ]
}